from calendar import c
from http import client
from math import log
from multiprocessing.connection import Client
from os import access
from select import select
from app.config.settings import get_settings
from app.modules.auth.manager import token_manager
from sqlalchemy import insert, select
from app.api.admin.model.client.client import ClientModel
from app.api.h5.schema.client.client import ClientInSchema, ClientOutSchema, LoginInSchema
import requests
from app.dependencies.database import db
from app.exceptions.exception import AppException
from app.exceptions.http_resp import HttpResp


class ClientService:
    @classmethod
    def instance(cls):
        return cls()

    async def login(self, login_in: LoginInSchema):
        params = {
            "appid": get_settings().wechat_appid or "wxb2f752875517d756",
            "secret": get_settings().wechat_secret or "31ec1639c2d0145c8624e07dc4d21e79",
            # "appid": get_settings().wechat_appid or "wx695c3bec76dee1eb",
            # "secret": get_settings().wechat_secret or "fdb191f2508da1839a784427a03ebd11",
            "code": login_in.code,
            "grant_type": "authorization_code"
        }
        print("params", params)
        # return {"token": 321321}
        # print("code", login_in.code)
        res = requests.get(
            url="https://api.weixin.qq.com/sns/oauth2/access_token", params=params)
        print("tengxun", res.json())
        openid = res.json().get("openid")
        if not openid:
            raise AppException(HttpResp.TOKEN_EMPTY, message="code 无效")

        # 使用 model_validate 方法创建 ClientInSchema 实例
        client_in = ClientInSchema.model_validate({
            "openid": openid,
        })

        client_id = await self.add(client_in)
        print(res.json().get("access_token"))
        print("用户id", client_id)
        if not client_id:
            raise AppException(HttpResp.SYSTEM_ERROR, message="用户不存在")
        token = token_manager.create_token(identity=client_id)
        return {"token": token}

    async def add(self, client_in: ClientInSchema):
        client_record = await db.fetch_one(select(ClientModel).where(ClientModel.openid == client_in.openid))
        if client_record:
            print("客户已经存在")
            return ClientOutSchema.model_validate(client_record, from_attributes=True).id
        add_id = await db.execute(insert(ClientModel).values(ClientInSchema.model_validate(client_in).model_dump()))
        return add_id
